package com.hudongwx.godoffood.activity.home_activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@ContentView(R.layout.activity_search)
public class SearchActivity extends AppCompatActivity {
    private String TAG = "SearchActivity";
    @ViewInject(R.id.search_input)
    EditText input;
    @ViewInject(R.id.search_list)
    ListView listView;
    @ViewInject(R.id.search_record)
    LinearLayout record;
    @ViewInject(R.id.search_bg)
    LinearLayout noRecord;


    private String inputContent;
    private SharedPreferences sharedPreferences;
    private String key;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        //SharedPreferences对应了一个xml的文件，用来存放数据
        sharedPreferences = getSharedPreferences("search", MODE_PRIVATE);

        input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //关闭软键盘
                InputMethodManager imm = (InputMethodManager) SearchActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(input.getWindowToken() , 0);

                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    //获取输入内容
                    inputContent = v.getText()+"";

                    key = System.currentTimeMillis()+"";
                    //获取到了一个编辑器
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //添加数据，这里存放在内存中，还没有持久化：没有把数据写入到磁盘
                    editor.putString(key,inputContent);
                    //写入到磁盘
                    editor.commit();

                    refreshRecord();
                    try {
                        //将搜索内容进行url编码
                        String inputContent2 =  java.net.URLEncoder.encode(inputContent,"utf-8");
                        Log.i(TAG, "onEditorAction: "+inputContent2);

                        loadSearch(inputContent2);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }
        });

        refreshRecord();

    }

    public void refreshRecord(){
        //显示搜索记录
        Map<String, ?> all = sharedPreferences.getAll();
        if (!all.isEmpty()){
            record.setVisibility(View.VISIBLE);
            noRecord.setVisibility(View.GONE);

            Set<? extends Map.Entry<String, ?>> entries = all.entrySet();
            List<String> list = new ArrayList<>();
            for(Map.Entry<String,?> entry:entries){
                list.add((String) entry.getValue());
            }
            listView.setAdapter(new ListAdapter(list));
        }else {
            record.setVisibility(View.GONE);
            noRecord.setVisibility(View.VISIBLE);
        }
    }

    class ListAdapter extends BaseAdapter{
        List<String> data;

        public ListAdapter(List<String> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view  = getLayoutInflater().inflate(R.layout.search_record,null);
            TextView textView = (TextView) view.findViewById(R.id.record);
            textView.setText(data.get(position));

            RecordItemListener listener = new RecordItemListener();
            view.setTag(data.get(position));
            view.setOnClickListener(listener);
            return view;
        }
    }

    //加载搜索结果
    public void loadSearch(String content){
        RequestParams params = new RequestParams(API.getSearchUrl(content));
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    //搜索状态
                    intent.putExtra("state", result.getInt("Status"));
                    //搜索框内容
                    intent.putExtra("input", input.getText()+"");
                    //将JSONArray转换为string通过intent传递到下一个页面
                    intent.putExtra("data", data.toString());
                    startActivity(intent);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    @Event(R.id.search_cancel)
    private void cancel(View view){
        finish();
    }
    //清除搜索记录
    @Event(R.id.search_clear)
    private void clear(View view){
        SharedPreferences.Editor edit=sharedPreferences.edit();//获取编辑器
        edit.clear();//删除
        edit.commit();//提交修改到磁盘里
        refreshRecord();
        Toast.makeText(this,"清除成功",Toast.LENGTH_SHORT).show();
    }

    @Event(R.id.search_bg)
    private void background(View view){
        //关闭软键盘
        InputMethodManager imm = (InputMethodManager) SearchActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken() , 0);
    }

    class RecordItemListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            try {
                String str = v.getTag()+"";
                //将搜索内容进行url编码
                String str2 =  java.net.URLEncoder.encode(str,"utf-8");
                input.setText(str);
                loadSearch(str2);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

}
